<template>
	<div class="group-list">

		<div class="option">
			<div class="adaption adaption-option">

                <div class="group-name">

                    <template v-if="!editing">
                        <div class="group-name-container" >
                            {{name}}
                        </div>
                        <span v-if="uid !== 'all' && isAdmin" @click="rename('key')" class="iconfont icon-editor"></span>
                        <div v-else class="group-count">({{total}}/{{memberLimit}})</div>
                    </template>
                    
                    <input v-else
                        @blur="stopEdit" 
                        v-on:keyup.enter="stopEdit" 
                        class="rename" 
                        v-model="name" 
                        type="text"
                        id="key">

                </div>
                <div class="group-btn-container">
                    <template v-if="isAdmin && uid !== 'all'">
                        <div class="dropdown-wrapper">
                            <g-button class="btn primary" type="primary" @click="addOrgMember">添加成员</g-button>
                            
                            <div class="chain-option-container">
                                <div @click="addOrgMember">
                                    添加组织成员
                                </div>
                                <div @click="addNewMember">
                                    邀请新成员
                                </div>
                            </div>
                    
                        </div>
                        <g-button class="btn del" @click="removeGroup">删除群组</g-button>
                    </template>
                </div>

			</div>
        </div>

        <org-member 
            v-if="orgMember"
            key='orgMember'
            :groups= groups
            :groupName= groupName
            :orgUid= orgUid
            :uid= uid
            v-on:close-org-member="closeOrgMember"
            v-on:update-group-members="updateGroupMembers">
        </org-member>

        <div class="group-list-container" >

            <div v-if="isEmpty" class="no-data">
                <img src="../../../static/img/no-data.png">  
                <div class="no-data-tip">该群组尚未添加成员</div>
            </div>

            <template v-else>
				 
                <div class="wrapper-body" :class="{'not-admin': !isAdmin}">
                    <div class="list-view-header adaption">
                        <div class="name">名称</div>
                        <div class="alias">姓名</div>
                        <div class="role">角色</div>
                        <div class="date">加入日期</div>
                        <div class="group-list-option" v-if="isAdmin">操作</div>
                    </div>
                    <g-scrollbar class="group-vertical-scroll">
                        <div class="adaption">
                            <div class="group-content">
                                <ul class="group-view">
                                    <li class="list-wrapper-group" v-for="item in groups">
                                        <div class="name">
                                            {{item.name}}
                                        </div>

                                        <div class="alias" v-bind:uid="item.uid">
                                            <span v-if="currentEditing != item.uid" class="alias-container">
                                                {{item.alias}}
                                            </span>
                                            <input
                                                v-else
                                                v-to-focus
                                                ref="alias"
                                                @blur="stopEditMember(item)"
                                                v-on:keyup.enter="stopEditMember(item)"
                                                class="realias" 
                                                v-model="item.alias"
                                                type="text">
                                        </div>

                                        <div class="role">{{item.role | roleFilter}}</div>
                                        <div class="date">{{item.createdAt | timeFormat}}</div>
                                        <div class="group-list-option" v-if="isAdmin">
                                            <i v-if="uid == 'all'"
                                            @click="editMember(item)" 
                                            class="iconfont"
                                            v-bind:class="ifEditMember !== item.uid ? classObject : editingClassObject" 
                                            title="编辑"></i>

                                            <i class="iconfont icon-delete" @click="remove(item.uid)"></i>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </g-scrollbar>
                </div>

            </template>
        	
        </div>
	</div>

</template>

<script>

	import GButton from '@/components/common/g-button'
	import GScrollbar from '@/components/common/g-scrollbar'
	import {group as groupAPI, organization as orgAPI} from '@/api'
	import { appNameMapping } from '@/config/config'
    import {format} from '@/utils/date'
    import md5 from 'crypto-js/md5'
    import OrgMember from './org-member'

	export default{
		name: 'group-list',
		
		data (){
			return {
                hasNext: false,
                isLoading: false,
                editing: false,
                orgUid: this.$root.org.orgUid,
                orgRole: this.$root.org.role,
                name: '',
                isEmpty: false,

                alias: '', //储存修改别名临时变量
                orgMember: false,
                currentEditing:'',
                ifEditMember:'',
                members:[],
                classObject: {
                    'icon-brush_fill': true,
                    'icon-loading': false,
                    'icon-spin': false
                },
                editingClassObject: {
                    'icon-brush_fill': false,
                    'icon-loading': true,
                    'icon-spin': true
                },
			}
		},

		components: {
			GButton,
            GScrollbar,
            OrgMember
		},

		props: {
			groups: Array,
            groupName: String,
            orgName: [String, undefined],
            uid: {
                type: String,
                default: 'all'
            },
            total: Number,
            memberLimit: Number,
		},
		
        computed: {
            isAdmin () {
                return this.orgRole === 'admin';
            },
        },

		activated () {
            this.name = this.groupName;
            this.$emit( 'on-view-load' );
        }, 

        filters: {
            timeFormat (val) {
                return format(String(val), 'Y-MM-DD hh:mm');
            },

            roleFilter (val) {
                return val === 'admin' ? '管理员' : '组员';
            }
        },

        watch: {
            groupName () {
                this.name = this.orgName || this.groupName;
            },

            groups (newVal, oldVal) {
                this.isEmpty = !newVal || !newVal.length;
                
            }

        },

		methods: {

            rename (id) {
                this.editing = true;

                this.$nextTick(function () {
                    document.getElementById(id).focus();
                })
            },

            async stopEdit () {

                this.editing = false;

                if (this.name === this.groupName) {
                    return;
                }

                let result = await groupAPI.rename(this.uid, {name: this.name});

                if (!result || result.data.code != 0) {
                    this.$message.error('重命名失败');
                    this.name = this.groupName;
                    return;
                }

                this.$message.success('重命名成功');
                this.$emit('rename', this.uid, this.name);
            },

            getAvatar (val) {
                const defaultAvatar = 'http://odqlwni8g.bkt.clouddn.com/geohey/static/img/default-avatar.png';
                return `url(https://www.gravatar.com/avatar/${ md5( val.email.toLowerCase() ) }?d=${ encodeURI( defaultAvatar ) }&s=80)`;
            },

            remove (memberUid) {

                let success = false;
                let tip = (this.uid === 'all') ? 
                    '该操作会将该成员从所有群组内移除，确认删除？':
                    `将该成员从${this.groupName}组内移除`
                let promise = this.$confirm(
                    tip, '删除',
                    {
                        type: 'warning',
                        confirmButtonType: 'danger',
                        confirmButtonText: '删除',
                        // parent: this.$refs.myData,
                        beforeClose: async (action, instance, done) => {

                            if (action === 'confirm') {
                                instance.confirmButtonLoading = true;
                                instance.confirmButtonText = '删除中...';
                                instance.cancelButtonDisabled = true;

                                let result = '';

                                if (this.uid === 'all') {
                                    result = await orgAPI.removeMember(this.orgUid, memberUid);
                                } else {
                                    result = await groupAPI.removeMember(this.uid, memberUid);
                                }

                                if (!result || result.data.code != 0) {
                                    this.$message.error('删除成员失败');
                                    done();
                                    return;
                                }

                                done();
                                success = true;
                                this.$message.success('删除成员成功');

                                instance.confirmButtonLoading = false;

                            } else {
                                done();
                            }

                        }
                    }
                );

                promise.then(() => {
                    if (!success) return;
                    this.$emit('remove-member', this.uid, memberUid)
                }).catch(() => {
                    // this.$message.error('取消')
                })
            },

            removeGroup () {
                this.$emit('remove-group', this.uid);
            },

            addNewMember () {

                if (this.total >= this.memberLimit) {
                    this.$alert(`当前组织共有成员 ${this.total} 人，已达到人数上限， 无法添加新成员`,'成员个数已达上限');
                    return;
                }

                let pattern = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;

                let promise = this.$prompt(' ', '添加成员', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPlaceholder: '输入用户邮箱',
                    // parent: this.$parent.$el,
                    startWaiting: (instance) => {
                        instance.editorErrorMessage = null;
                        instance.$refs.input.classList.remove('invalid');

                        instance.confirmButtonLoading = true;
                        instance.confirmButtonText = '操作中...';
                        instance.cancelButtonDisabled = true;
                    },
                    stopWaiting: (instance) => {
                        instance.confirmButtonLoading = false;
                        instance.confirmButtonText = '确定';
                        instance.cancelButtonDisabled = false;
                    },
                    beforeClose: async(action, instance, done) => {

                        let result = '';

                        if (action === 'confirm') {

                            let inputValue = instance.inputValue;

                            let ok = pattern.test(inputValue);

                            if (!ok) {
                                instance.editorErrorMessage = '邮箱地址格式错误';
                                instance.$refs.input.classList.add('invalid');
                                return;
                            }

                            instance.startWaiting(instance);

                            let result = await groupAPI.invite(this.uid, { email: inputValue });

                            if (!result) {
                                this.$message.error('获取成员失败');
                                return;
                            }

                            if (result.data.code == 701) {
                                instance.editorErrorMessage = '用户不存在';
                                instance.$refs.input.classList.add('invalid');
                                instance.stopWaiting(instance);
                                return;
                            }

                            if (result.data.code == 613) {
                                instance.editorErrorMessage = '用户已存在于该群组';
                                instance.$refs.input.classList.add('invalid');
                                instance.stopWaiting(instance);
                                return;
                            }

                            if (result.data.code != 0)  {
                                this.$message.error('添加成员失败');
                                instance.stopWaiting(instance);
                                return;
                            }

                            instance.editorErrorMessage = null;
                            instance.$refs.input.classList.remove('invalid');

                            this.$message.success('邀请已发出，等待确认');
                            done();

                        } else {
                            done();
                        }
                    }
                })

                promise.then(async ( {value} ) => { }).catch(() => { });
                
            },
                
            editMember (item) {
                this.currentEditing = item.uid;
                //储存姓名变量，修改失败时恢复
                this.alias=item.alias;
            },

            async stopEditMember (item){

                let reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/;

                if(item.alias === this.alias){
                    this.currentEditing = '';
                    return;
                }

                if(item.alias.length < 2 || item.alias.length > 10){
                    this.$message.error('姓名长度为2-10个字符串');
                    this.$refs.alias[0].focus();
                    item.alias = this.alias;
                    return;
                }

                if(!reg.test(item.alias)){
                    this.$message.error('请输入中文、字母或数字。');
                    this.$refs.alias[0].focus();
                    item.alias = this.alias;
                    return;
                }

                this.currentEditing = '';

                this.ifEditMember = item.uid;
                let result = await orgAPI.updateMember(this.orgUid, item.uid,item.alias);
                this.ifEditMember ='';

                if (result && result.data.code === 612 ) {
                    this.$message.error('输入名称不合法');
                    item.alias = this.alias;
                    return;
                }

                if (!result || result.data.code != 0) {
                    this.$message.error('重命名失败');
                    item.alias = this.alias;
                    return;
                }

                this.$message.success('重命名成功');

                this.$emit('reset-member');
            },

            addOrgMember () {
                this.orgMember = true;
            },

            closeOrgMember () {

                this.orgMember = false;
            },

            updateGroupMembers (choosedMembers,key) {
                this.$emit('update-group-members',choosedMembers,key);
            }

        },

        directives: {
            "to-focus" : function (el) {
                setTimeout(() => {el.focus()});
            }
        },

	}
</script>

<style lang="scss">

	@import 'common';
	
	.group-list {

		height: 100%;
		width: 100%;
		position: relative;

		.adaption {

            margin: 0 auto;
            position: relative;
            min-width: 510px;

           	@media screen and (min-width: 1741px) {
                max-width: 1320px;
            }
            @media screen and (max-width: 1740px) {
                max-width: 1050px;
            }
            @media screen and (max-width: 1560px) {
                max-width: 780px;
            }
            @media screen and (max-width: 1200px) {
                max-width: 510px;
            }

		}

		.option{
            
            padding: 19px 0;
            width: 100%;
            overflow: visible;
            position: absolute;

            .adaption-option {

            	overflow: visible;

                .group-name {

                    width: 100%;
                    height: 30px;
                    padding-right: 200px;
                    line-height: 30px;

                    .group-name-container {

                        float: left;
                        height: 100%;
                        line-height: 30px;
                        font-size: 16px;
                        color: $dark;
                        @include text-overflow();
                        padding-right: 28px;
                        
                    }

                    >span {
                        color: $gray;
                        float: left;
                        margin-left: 6px;
                        position: relative;
                        left: -20px;
                        cursor: pointer;

                        &:hover {
                            color: $info;
                        }
                    }

                    .group-count {
                        float: left;
                        color: $gray;
                        position: relative;
                        left: -20px;
                        font-size: 12px;
                        line-height: 34px;
                    }

                    .rename {
                        height: 100%;
                        width: 100%;
                        max-width: 200px;
                        font-size: 16px;
                        color: $deepGray;
                        border-bottom: 1px solid $bdGray;
                    }
                }

                .group-btn-container {
                    position: absolute;
                    right: 0;
                    top: 0;

                    >.btn {
                        width: 90px;
                    }

                    >.btn.del:hover {
                        color: $danger !important;
                        border-color: $danger !important;
                    }
                }
            }

        }

        .group-list-container {

            padding: 68px 0 64px 0;
            height: 100%;

            .no-data{
                text-align: center;
                position: absolute;
                width: 100%;
                top: 50%;
                transform:translate(0, -100%);
                @include user-select(none);

                .no-data-tip {
                    font-size: 14px;
                    margin-top: 16px;
                    color: $gray;
                }
            }

            .wrapper-body.not-admin {
                .list-view-header > div {
                    width: 25% !important;
                }

                .list-wrapper-group > div {
                    width: 25% !important;
                }
            }

            .wrapper-body {
                height: 100%;

                .list-view-header {

                    height: 50px;
                    padding: 8px 0;
                    line-height: 32px;
                    font-size: 13px;
                    color: $gray;
                    border-top: 1px solid $bdGray;
                    border-bottom: 1px solid $bdGray;

                    > div {
                        float: left;
                        height: 100%;
                        width: 20%;
                    }

                    >.name {
                        padding: 0 4px;
                        position: relative;
                        text-align: left;
                        @include text-overflow();
                    }

                    >.role {
                        text-align: left;
                    }

                    >.date {
                        text-align: right;
                    }

                    >.group-list-option {
                        text-align: center;
                    }
                }

                .group-vertical-scroll {
                    width: 100%;
                    height: calc(100% - 50px);

                    .g-scrollbar-scrollbar-vertical{
                        width: 10px;
                    }

                    .scrollbar{
                        display: block !important;
                        width: 10px;
                        background-color: #9e9e9e;
                    }

                    .scrollbar.g-scrollbar-transition {
                        width: 10px;
                    }
                }

                .group-content {
                    margin: 0 -15px;
                    .group-view {
                        overflow: hidden;

                        .list-wrapper-group {

                            overflow: hidden;
                            border-bottom: 1px solid $bdGray;
                            height: 50px;
                            padding: 8px 0;
                            line-height: 32px;
                            margin: 0 15px;

                            >div {
                                float: left;
                                height: 100%;
                                width: 20%;
                            }

                            >.name {
                                padding: 0 4px;
                                overflow: hidden;
                                text-align: left;
                                @include text-overflow();
                            }

                            >.role {
                                text-align: left;
                            }

                            >.date {
                                text-align: right;
                            }

                            >.group-list-option {

                                text-align: center;

                                >i {
                                    font-size: 14px;
                                    margin-left: 6px;
                                    color: $gray;
                                    cursor: pointer;
                                }

                                .icon-delete:hover {
                                    color: $danger;
                                }
                            }

                            .alias{
                                overflow: hidden;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                            }

                        }
                    }
                }

                .add-more-wrapper {
                    width: 88px;
                    height: 26px;
                    margin: 36px auto;

                    .add-more {
                        cursor: pointer;
                        border-radius: 12px;
                        color: $gray;
                        font-size: 12px;
                        line-height: 22px;
                        margin: auto;
                        text-align: center;
                        white-space: nowrap;
                        vertical-align: middle;
                        width: 86px;
                        height: 24px;
                        border: 1px solid $bdGray;
                        background-color: transparent;

                        i{
                            font-size: 12px;
                        }

                        &:hover{
                            border: 1px solid darker($bdGray, 10%);
                        }
                    }
                }
            }
        }
    }
    .realias{
        height: 100%;
        width: 90%;
        max-width: 200px;
        font-size: 12px;
        cursor: text;
        font-weight: 400;
        color: $deepGray;
        border: 1px solid $bdGray;
        padding-left: 6px;
        border-radius: 4px;

        &:focus{
            border-color: #4087f7;
        }
    }
    .icon-brush_fill:hover{
        color:$primary !important;
    }
    .addMember{
        display: inline-block;
    }
    .arrow{
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 6x solid #ccc;
        border-bottom: 0;
    }
    .dropdown-wrapper{
        cursor: pointer;
        display: inline-block;
        overflow: visible;
        height: 40px;

        .btn{
            min-width: 90px;
        }
        &:hover{
            .chain-option-container{
                position: absolute;
                z-index: 500;
                min-width: 90px;
                display: inline-block;
                background-color: $bgWhite;
                border-radius: $bdRadius;
                border: 1px solid $bdGray;
                text-align: left;
                color: $gray;
                padding: 6px 0;            
                margin-top: 10px;
                >div {
                    padding: 4px 20px;
                    cursor: pointer;
                    white-space: nowrap;
                    font-size: 12px;

                    &:hover{
                        color: $deepGray;
                        background-color: #e8eef6;
                    }
                }

                &::before{
                    content: "";
                    width: 0;
                    height: 0;
                    position: absolute;
                    right: 68px;
                    top: -10px;
                    border-bottom: solid 10px #d4d8db;
                    border-left: solid 8px transparent;
                    border-right: solid 8px transparent;
                }

                &::after{
                    content: "";
                    width: 0;
                    height: 0;
                    position: absolute;
                    right: 70px;
                    top: -8px;
                    border-bottom: solid 8px white;
                    border-left: solid 6px transparent;
                    border-right: solid 6px transparent;
                }
            }
        }
        .chain-option-container{
            display: none;
        }

    }
</style>